// 苹果CMS api接口采集
import { NextFunction, Request, Response, Router } from "express";
import { BaseController } from "../BaseController";
import { Utils } from "../../utils";
import { CONFIG } from "../../config";
import { isNumber } from "util";
import { MySql } from "../DB/MySql";
import { HTTPOperation } from "../HTTP";
import { XMLOperation } from "../XML";
const readline = require('readline');

export class PGApiController extends BaseController {


    private mysqlDB: any;
    private pageData = {
        page: 1,
        pagecount: 0,
        pagesize: 0,
        recordcount: 0
    };

    /**
     * Constructor
     *
     * @class PGApiController
     * @constructor
     */
    constructor() {
        super();
        this.mysqlDB = new MySql();
    }



    /**
     * 暂停采集服务
     * @param req 
     * @param res 
     * @param next 
     */
    public stopService(req: Request, res: Response, next: NextFunction) {
        setInterval(() => {
            CONFIG.runState = false;
        }, 1); 
        res.json(this.ResultMsg("正在停止...."));
    }


    /**
     * 开始采集服务
     * @param req 
     * @param res 
     * @param next 
     */
    public startService(req: Request, res: Response, next: NextFunction) {
        let $this = this;
        CONFIG.runState = true;
        this.mysqlDB.query("select * from g_gather_info where state=1").then((retData) => {
            if (retData.length > 0) {
                retData.forEach(element => {
                    let url = element["source"];
                    let id = element["id"];
                    let page = element["page"];
                    let last = element["last"];
                    let complete = element["complete"];
                    if (complete == 1) {
                        $this.ParsetLast(url, id, last);
                    }
                    else { 
                        $this.ParsetPage(url, id, page);
                    }
                });
            }
        }).catch((error) => {
            console.log(error);
        });
        res.json($this.ResultMsg("正在启动...."));
    }


    /**
     * 新增采集
     * @param req 
     * @param res 
     * @param next 
     */
    public addService(req: Request, res: Response, next: NextFunction) {
        let $this = this;

        console.log(req.params);
        $this.mysqlDB.insert("INSERT INTO g_gather_info (`last`,`page`,`source`,`type`) VALUES( '" + Utils.getNowFormatDate() + "', 1, '" + req.params.url + "','" + req.params.type + "')").then((addData) => {
            if (addData.insertId != undefined) {
                this.ParsetPage(req.params.url, addData.insertId, 1);
            }
        }).catch((error) => {
            console.log(error);
        });

        res.json($this.ResultMsg("正在添加线程处理...."));
    }


    /**
      * 采集指定连接的更新数据
      * @param url 
      * @param id 
      * @param page 
      */
    public ParsetLast(url, id, last) {
        let $this = this;
        let xMLOperation = new XMLOperation();
        let httpClient = new HTTPOperation();
        let urlAddress = url + `/provide/vod/at/xml/?ac=videolist&pg=1`;
        httpClient.getURL(urlAddress).then((data) => {
            let json2xml = xMLOperation.Parser(data);
            $this.pageData = json2xml["page"];
            $this.gatherLastList(1, last, url, $this, id);
        }).catch((error) => {
        });
    }

    /**
      * 采集指定页码所有的数据
      * @param start 
      * @param last 
      * @param url 
      * @param $this 
      * @param id 
      */
    private gatherLastList(start, last, url, $this, id) {
        if ($this.myTime != null) {
            clearTimeout($this.myTime);
        }
        let xMLOperation = new XMLOperation();
        let httpClient = new HTTPOperation();
        let urlAddress = url + `/provide/vod/at/xml/?ac=videolist&pg=` + start;
        httpClient.getURL(urlAddress).then((data) => {
            let json2xml = xMLOperation.Parser(data);
            let bo = $this.XMLSQL(json2xml["video"], $this, urlAddress, last, id);
            start++;
            if (bo) {
                $this.myTime = setTimeout(function () {
                    console.log("第" + start + "页数据:" + url + `/provide/vod/at/xml/?ac=videolist&pg=` + start);
                    console.log("gatherLastList:" + CONFIG.runState);
                    $this.gatherLastList(start, last, url, $this, id);
                }, 1000);
            }

        }).catch((error) => { });
    }


    /**
     * 采集指定连接的页码数据
     * @param url 
     * @param id 
     * @param page 
     */
    public ParsetPage(url, id, page) {
        let $this = this;
        let xMLOperation = new XMLOperation();
        let httpClient = new HTTPOperation();
        let urlAddress = url + `/provide/vod/at/xml/?ac=videolist&pg=` + page;
        httpClient.getURL(urlAddress).then((data) => {
            let json2xml = xMLOperation.Parser(data);
            $this.pageData = json2xml["page"];
            let incision = $this.pageData.pagecount;
            $this.gatherPageList(page, incision, url, $this, id);
        }).catch((error) => {
        });
    }


    private myTime;
    /**
     * 采集指定页码所有的数据
     * @param start 
     * @param end 
     * @param url 
     * @param $this 
     * @param id 
     */
    private gatherPageList(start, end, url, $this, id) {
        if ($this.myTime != null) {
            clearTimeout($this.myTime);
        }
        let xMLOperation = new XMLOperation();
        let httpClient = new HTTPOperation();
        if (start <= end) {
            let urlAddress = url + `/provide/vod/at/xml/?ac=videolist&pg=` + start;

            httpClient.getURL(urlAddress).then((data) => {
                let json2xml = xMLOperation.Parser(data);
                let bo = $this.XMLSQL(json2xml["video"], $this, urlAddress, null, id);
                start++;
                if (bo && CONFIG.runState) {
                    $this.myTime = setTimeout(function () {
                        console.log("第" + start + "页数据:" + url + `/provide/vod/at/xml/?ac=videolist&pg=` + start);
                        $this.gatherPageList(start, end, url, $this, id);
                    }, 3000)
                }
                else {
                    $this.mysqlDB.update("update g_gather_info set page =" + start + "  where  id=" + id).then((retData) => {
                        console.log("终止采集队列:" + id);
                    }).catch(() => { });
                }
            }).catch((error) => {
            });
        }
        else {
            $this.mysqlDB.update("update g_gather_info set complete =1  where  id=" + id).then((retData) => {
                console.log("采集队列:" + id + "已完成");
            }).catch(() => { });
        }
    }

    public XMLSQL(videoList, $this, urlAddress, last, id) {
        var bo = true;
        videoList.forEach(element => {
            let name = element.name.split('#')[0];
            name = Utils.excludeSpecial(name);
            let des = Utils.excludeSpecial(element.des);
            let actor = Utils.excludeSpecial(element.actor);
            let director = Utils.excludeSpecial(element.director);
            let pic = element.pic.split('#')[0];
            //采集到过期数据终止采集 
            let a = new Date(last);
            let b = new Date(element.last);
            if (last != undefined && last != null && b <= a) {

                bo = false;
                return bo;
            }
            if (element.collect.length > 0) {
                $this.mysqlDB.query("select * from g_video where name='" + name + "' ").then((retData) => {
                    if (retData.length == 0) {
                        $this.mysqlDB.insert("INSERT INTO g_video (`last`,`tid`,`name`,`type`,`pic`,`lang`,`area`,`year`,`note`,`actor`,`director`,`des`,`source`,`create_time`,`gather_id`) VALUES( '" + element.last + "', '" + element.tid + "', '" + name + "', '" + element.type + "', '" + pic + "', '" + element.lang + "', '" + element.area + "', '" + element.year + "', '" + element.note + "','" + actor + "', '" + director + "', '" + des + "', '" + urlAddress + "', '" + new Date().getTime() / 1000 + "'," + id + ")").then((addData) => {
                            readline.clearLine(process.stdout, 0);
                            readline.cursorTo(process.stdout, 0, 0)
                            process.stdout.write("找到影片:" + name + " 播放地址" + element.collect.length + "个,正在添加......", 'utf-8');

                            console.log();
                            if (addData.insertId != undefined) {
                                element.collect.forEach(item => {
                                    $this.mysqlDB.query("select * from g_video_film_source where video_id=" + addData.insertId + " and type='" + item.type + "' and name ='" + item.name + "'").then((queryData) => {
                                        if (queryData.length > 0) {

                                        }
                                        else {
                                            $this.mysqlDB.insert("INSERT INTO g_video_film_source (`name`,`url`,`type`,`video_id`,`create_time`) VALUES( '" + item.name + "', '" + item.url + "', '" + item.type + "','" + addData.insertId + "', '" + new Date().getTime() / 1000 + "')").then((addData) => {
                                            }).catch((error) => {
                                                console.log(error);
                                            });
                                        }
                                    }).catch((error) => {
                                        console.log(error);
                                    })
                                });
                            }
                        }).catch((error) => {
                            console.log(error);
                        });
                    }
                    else {
                        let data = retData[0];

                        readline.clearLine(process.stdout, 0);
                        readline.cursorTo(process.stdout, 0, 0)
                        process.stdout.write("找到影片:" + name + " 播放地址" + element.collect.length + "个,正在添加......", 'utf-8');
                        element.collect.forEach(item => {
                            $this.mysqlDB.query("select * from g_video_film_source where video_id=" + data.id + " and type='" + item.type + "' and name ='" + item.name + "'").then((queryData) => {
                                if (queryData.length > 0) {

                                }
                                else {
                                    $this.mysqlDB.insert("INSERT INTO g_video_film_source (`name`,`url`,`type`,`video_id`,`create_time`) VALUES( '" + item.name + "', '" + item.url + "', '" + item.type + "','" + data.id + "', '" + new Date().getTime() / 1000 + "')").then((addData) => {

                                    }).catch((error) => {
                                        console.log(error);
                                    });
                                }
                            }).catch((error) => {
                                console.log(error);
                            })
                        });
                    }
                }).catch((error) => {
                    console.log(error);
                });
            }
        });
        return bo;
    }




}
